package com.xuecheng.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.CourseView;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.CmsPostPageResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.domain.course.response.CoursePublishResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.dao.*;
import com.xuecheng.manage_course.feign_client.CmsPageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CourseService {
    @Autowired
    TeachPlanMapper teachPlanMapper;
    @Autowired
    CourseBaseRepository courseBaseRepository;
    @Autowired
    TeachPlanRepository teachPlanRepository;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    CourseMarketRepository courseMarketRepository;
    @Autowired
    CoursePicRepository coursePicRepository;
    @Autowired
    CmsPageClient cmsPageClient;
    @Autowired
    CoursePubRepository coursePubRepository;
    @Autowired
    TeachplanMediaRepository teachplanMediaRepository;
    @Autowired
    TeachplanMediaPubRepository teachplanMediaPubRepository;

    @Value("${course‐publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course‐publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course‐publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course‐publish.siteId}")
    private String publish_siteId;
    @Value("${course‐publish.templateId}")
    private String publish_templateId;
    @Value("${course‐publish.previewUrl}")
    private String previewUrl;


    public TeachplanNode findTeachPlanList(String courseId){
        return teachPlanMapper.selectList(courseId);
    }

    @Transactional
    public ResponseResult addTeachPlan(Teachplan teachplan) {
        if(teachplan==null
                || StringUtils.isEmpty(teachplan.getCourseid())
                ||StringUtils.isEmpty(teachplan.getPname())){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        String courseId=teachplan.getCourseid();
        String parentId=teachplan.getParentid();
        //如果父节点为空 则获取根节点
        if(StringUtils.isEmpty(parentId)){
            parentId=getTeachplanRoot(courseId);
        }
        Optional<Teachplan> teachplanOptional=teachPlanRepository.findById(parentId);
        Teachplan parent=teachplanOptional.get();
        Teachplan teachplanNew=new Teachplan();
        //将页面提交的teachPlan信息拷贝到新节点中
        BeanUtils.copyProperties(teachplan,teachplanNew);
        teachplanNew.setParentid(parentId);
        teachplanNew.setCourseid(courseId);
        //Grade级别设置要根据父节点的级别来设置
        if(parent.getGrade().equals("1")){
            teachplanNew.setGrade("2");
        }else {
            teachplanNew.setGrade("3");
        }
        teachPlanRepository.save(teachplanNew);
        return new ResponseResult(CommonCode.SUCCESS);
    }
    //根据课程id获取根节点id
   private String getTeachplanRoot(String courseId){
        //根据课程ID获取课程信息
       Optional<CourseBase> optional=courseBaseRepository.findById(courseId);
       if(!optional.isPresent()){
           return null;
       }
       CourseBase courseBase=optional.get();
      List<Teachplan> teachplanList= teachPlanRepository.findTeachplanByCourseidAndParentid(courseId,"0");
      if(teachplanList==null||teachplanList.size()==0){
          //若根节点为空，需要添加根节点
          Teachplan teachplanRoot=new Teachplan();
          teachplanRoot.setParentid("0");
          teachplanRoot.setGrade("1");
          teachplanRoot.setCourseid(courseId);
          teachplanRoot.setPname(courseBase.getName());
          teachPlanRepository.save(teachplanRoot);
          return teachplanRoot.getId();
      }
      return teachplanList.get(0).getId();
   }

   //查询课程列表
    public QueryResponseResult<CourseInfo> findCourseList(String companyId,int page, int size, CourseListRequest courseListRequest) {
        if(courseListRequest==null){
            courseListRequest=new CourseListRequest();
        }
        courseListRequest.setCompanyId(companyId);
        if(page<=0){
            page=1;
        }
        if(size<=0){
            size=10;
        }
        PageHelper.startPage(page,size);
        Page<CourseInfo> list=courseMapper.findCourseListPage(courseListRequest);
        List<CourseInfo> result=list.getResult();
        QueryResult queryResult=new QueryResult();
        queryResult.setList(result);
        queryResult.setTotal(list.getTotal());
        QueryResponseResult<CourseInfo> queryResponseResult=new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);
        return queryResponseResult;
    }

    //新增课程方法
    public ResponseResult addCourseBase(CourseBase courseBase) {
        if(courseBase==null||StringUtils.isEmpty(courseBase.getId())||StringUtils.isEmpty(courseBase.getName())){
          ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CourseBase newCourse=courseBaseRepository.getOne(courseBase.getId());
        if(newCourse!=null){
            ExceptionCast.cast(CourseCode.COURSE_BASE_ISEXITS);
        }

        BeanUtils.copyProperties(courseBase,newCourse);
        courseBaseRepository.save(newCourse);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //修改课程方法
    @Transactional
    public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
        if (StringUtils.isEmpty(id)){
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Optional<CourseBase> upCourse=courseBaseRepository.findById(id);
        if(!upCourse.isPresent()||courseBase==null){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CourseBase newCourse=upCourse.get();
        BeanUtils.copyProperties(courseBase,newCourse);
        courseBaseRepository.save(newCourse);
        return new ResponseResult(CommonCode.SUCCESS);
    }


    public CourseBase getCouseBaseById(String courseId) {
        if(StringUtils.isEmpty(courseId)){
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Optional<CourseBase> optional=courseBaseRepository.findById(courseId);
        if(!optional.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CourseBase courseBase=optional.get();
        return courseBase;
    }

    //通过课程ID查询营销信息
    public CourseMarket getCourseMarketById(String courseId) {
        if(StringUtils.isEmpty(courseId)){
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Optional<CourseMarket> optional=courseMarketRepository.findById(courseId);
        if(!optional.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        return optional.get();
    }

    //更新营销信息
    @Transactional
    public ResponseResult updateCourseMarket(String id, CourseMarket courseMarket) {
        if(StringUtils.isEmpty(id)){
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Optional<CourseMarket> optional=courseMarketRepository.findById(id);
        if(!optional.isPresent()||courseMarket==null){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CourseMarket newCourse=new CourseMarket();
        BeanUtils.copyProperties(courseMarket,newCourse);
        courseMarketRepository.save(newCourse);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Transactional
    public ResponseResult saveCoursePic(String courseId, String pic) {
        //查询课程图片
        Optional<CoursePic> picOptional = coursePicRepository.findById(courseId);
        CoursePic coursePic = null;
        if(picOptional.isPresent()){
            coursePic = picOptional.get();
        }
        //没有课程图片则新建对象
        if(coursePic == null){
            coursePic = new CoursePic();
        }
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        //保存课程图片
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);

    }

    public CoursePic findCoursePic(String courseId) {
        Optional<CoursePic> optional=coursePicRepository.findById(courseId);
        if(!optional.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CoursePic coursePic=optional.get();
        return coursePic;
    }
    //删除图片
    @Transactional
    public ResponseResult deleteCoursePic(String courseId) {
      Integer result=  coursePicRepository.deleteByCourseid(courseId);
        if (result > 0) {
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }
    //课程视图查询
    public CourseView getCourseView(String id) {
        CourseView courseView = new CourseView();
        //查询课程基本信息
        Optional<CourseBase> optional = courseBaseRepository.findById(id);
        if(optional.isPresent()){
            CourseBase courseBase = optional.get();
            courseView.setCourseBase(courseBase);
        }
        //查询课程营销信息
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
        if(courseMarketOptional.isPresent()){
            CourseMarket courseMarket = courseMarketOptional.get();
            courseView.setCourseMarket(courseMarket);
        }
        //查询课程图片信息
        Optional<CoursePic> picOptional = coursePicRepository.findById(id);
        if(picOptional.isPresent()){
            CoursePic coursePic = picOptional.get();
            courseView.setCoursePic(coursePic);
        }
        //查询课程计划信息
        TeachplanNode teachplanNode = teachPlanMapper.selectList(id);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }

    //课程预览
    public CoursePublishResult preview(String id) {
        CourseBase one = this.findCourseBaseById(id);
        //发布课程预览页面
        CmsPage cmsPage = new CmsPage();
        //站点
        cmsPage.setSiteId(publish_siteId);//课程预览站点
        //模板
        cmsPage.setTemplateId(publish_templateId);
        //页面名称
        cmsPage.setPageName(id+".html");
        //页面别名
        cmsPage.setPageAliase(one.getName());
        //页面访问路径
        cmsPage.setPageWebPath(publish_page_webpath);
        //页面存储路径
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        //数据url
        cmsPage.setDataUrl(publish_dataUrlPre+id);
        //远程请求cms保存页面信息
        CmsPageResult cmsPageResult = cmsPageClient.saveCmsPage(cmsPage);
        if(!cmsPageResult.isSuccess()){
            return new CoursePublishResult(CommonCode.FAIL,null);
        }
        //页面id
        String pageId = cmsPageResult.getCmsPage().getPageId();
        //页面url
        String pageUrl = previewUrl+pageId;
        return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);

    }

    private CourseBase findCourseBaseById(String id) {
        Optional<CourseBase> baseOptional = courseBaseRepository.findById(id);
        if(baseOptional.isPresent()){
            CourseBase courseBase=baseOptional.get();
            return courseBase;
        }
        ExceptionCast.cast(CourseCode.COURSE_GET_NOTEXISTS);
        return null;
    }

    //课程发布
    @Transactional
    public CoursePublishResult publish(String id) {
        CourseBase one = this.findCourseBaseById(id);
        //准备页面信息
        CmsPage cmsPage = new CmsPage();
        //站点
        cmsPage.setSiteId(publish_siteId);//课程预览站点
        //模板
        cmsPage.setTemplateId(publish_templateId);
        //页面名称
        cmsPage.setPageName(id+".html");
        //页面别名
        cmsPage.setPageAliase(one.getName());
        //页面访问路径
        cmsPage.setPageWebPath(publish_page_webpath);
        //页面存储路径
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        //数据url
        cmsPage.setDataUrl(publish_dataUrlPre+id);
        //远程请求cms发布页面
        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        if(!cmsPostPageResult.isSuccess()){
            return new CoursePublishResult(CommonCode.FAIL,null);
        }
        //保存课程信息为已发布状态
        CourseBase courseBase=this.saveCourseState(id);
        //保存课程索引信息
        //先创建一个coursePub对象
        CoursePub coursePub= this.createCoursePub(id);
        //将coursePub保存到数据库
        this.saveCoursePub(id,coursePub);
        //获取pageUrl
        String pageUrl=cmsPostPageResult.getPageUrl();
        //向teachPlanMediaPub中保存课程信息
        this.saveTeachplanMediaPub(id);
        return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);
    }

    //保存课程计划媒资信息
    public void saveTeachplanMediaPub(String courseId){
        teachplanMediaPubRepository.deleteByCourseId(courseId);
     List<TeachplanMedia>  teachplanMediaList=teachplanMediaRepository.findAllByCourseId(courseId);
        List<TeachplanMediaPub> teachplanMediaPubs=new ArrayList<>();
        for (TeachplanMedia teachPlanMedia:teachplanMediaList
             ) {
            TeachplanMediaPub teachplanMediaPub=new TeachplanMediaPub();
            BeanUtils.copyProperties(teachPlanMedia,teachplanMediaPub);
            teachplanMediaPub.setTimestamp(new Date());
         teachplanMediaPubs.add(teachplanMediaPub);
        }
     teachplanMediaPubRepository.saveAll(teachplanMediaPubs);
    }

    //保存或更新coursePub对象
    private CoursePub saveCoursePub(String id,CoursePub coursePub){
        //根据id获取CoursePub
        CoursePub newCoursePub=null;
        Optional<CoursePub> optional=coursePubRepository.findById(id);
        if(optional.isPresent()){
            newCoursePub=optional.get();
        }else {
            newCoursePub=new CoursePub();
        }
        BeanUtils.copyProperties(coursePub,newCoursePub);
        //设置逐渐
        newCoursePub.setId(id);
        //更新时间戳 给logstach使用
//        TimeZone time=TimeZone.getTimeZone("ETC/GMT-8");
//        TimeZone.setDefault(time);
        newCoursePub.setTimestamp(new Date());
        //发布时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY‐MM‐dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        newCoursePub.setPubTime(date);
        coursePubRepository.save(newCoursePub);
        return newCoursePub;
    }
    //创建coursePub方法
    private CoursePub createCoursePub(String id){
        CoursePub coursePub=new CoursePub();
        //获取courseBase基础信息
        Optional<CourseBase> optional=courseBaseRepository.findById(id);
        if(optional.isPresent()){
            CourseBase courseBase=optional.get();
            BeanUtils.copyProperties(courseBase,coursePub);
        }
        //查询课程图片
        Optional<CoursePic> picOptional = coursePicRepository.findById(id);
        if(picOptional.isPresent()){
            CoursePic coursePic = picOptional.get();
            BeanUtils.copyProperties(coursePic, coursePub);
        }
        //课程营销信息
        Optional<CourseMarket> marketOptional = courseMarketRepository.findById(id);
        if(marketOptional.isPresent()){
            CourseMarket courseMarket = marketOptional.get();
            BeanUtils.copyProperties(courseMarket, coursePub);
        }

        //获取teachPlan 将teachPlan转换成json串放入coursePub中
        TeachplanNode teachplanNode=teachPlanMapper.selectList(id);
        //转换为JSON串
        String teachPlanString=JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(teachPlanString);
        return coursePub;
    }

    //更改课程状态 202002为已发布状态
    private CourseBase saveCourseState(String courseId) {
    CourseBase courseBase=this.findCourseBaseById(courseId);
    courseBase.setStatus("202002");
    CourseBase sava= courseBaseRepository.save(courseBase);
    return sava;
    }

    //保存课程计划与媒资关联信息
    public ResponseResult saveMedia(TeachplanMedia teachplanMedia) {
        if(teachplanMedia == null){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //获取课程计划
        String teachPlanId=teachplanMedia.getTeachplanId();
       Optional<Teachplan> optional=teachPlanRepository.findById(teachPlanId);
       if(!optional.isPresent()){
           ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_ISNULL);
       }
       Teachplan teachplan=optional.get();
        //只允许为叶子结点课程计划选择视频
        String grade = teachplan.getGrade();
        if(StringUtils.isEmpty(grade) || !grade.equals("3")){
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_GRADEERROR);
        }
        //获取TeachPlanMedia
        TeachplanMedia one=null;
        Optional<TeachplanMedia> mediaOptional=teachplanMediaRepository.findById(teachPlanId);
        if(!mediaOptional.isPresent()){
            one = new TeachplanMedia();
        }else {
            one=mediaOptional.get();
        }
        //将各属性set到TeachPlanMedia并保存
        one.setTeachplanId(teachPlanId);
        one.setCourseId(teachplanMedia.getCourseId());
        one.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
        one.setMediaId(teachplanMedia.getMediaId());
        one.setMediaUrl(teachplanMedia.getMediaUrl());
        teachplanMediaRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
